from DrissionPage import ChromiumOptions, Chromium
from DrissionPage.common import Keys
import sys


def to_douyin(vide_file: str, title: str, description: str, tags_list: list):
    if sys.platform == 'darwin':
        # 系统是 macOS ，设置edge浏览器路径
        path = r'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'
        ChromiumOptions().set_browser_path(path).save()

    # 启动或接管浏览器，并获取标签页对象
    browser = Chromium().latest_tab

    # 打开页面
    browser.get('https://creator.douyin.com/creator-micro/content/post/video?enter_from=publish_page')
    browser.wait.doc_loaded()

    # 查找【上传按钮】
    upload_buttons = browser.eles('.^upload-card-null-')
    if len(upload_buttons) > 0:
        upload_button = upload_buttons[0]
        # 点击【上传按钮】，并上传指定视频文件
        upload_button.click.to_upload(vide_file)
        browser.wait(1)

    # 输入标题
    browser.ele('.semi-input semi-input-default').input(title)
    browser.wait(1)

    # 输入简介
    editor_act = browser.actions.click('.:zone-container editor-kit-container editor').input(description)
    browser.wait(1)

    # 标签列表
    for i in tags_list:
        editor_act.type('#').input(i).type(Keys.ENTER)
    browser.wait(1)

    # 滚动到底部
    browser.scroll.to_bottom()
    browser.wait(1)

    # # 点击发布按钮
    browser.ele('@text()=发布').click()
    browser.wait(1)


def to_douyin_from_cmd():
    """
     python main.py path/to/video 标题 描述 标签1,标签2,标签3
    :return:
    """
    args = sys.argv

    if len(args) < 4:
        exit()

    video_file_input = args[1]
    title_input = args[2]
    description_input = args[3]

    tags_list_input = []
    if len(args) > 4:
        for i in args[4].split(','):
            if i:
                tags_list_input.append(i.strip())

    to_douyin(
        vide_file=video_file_input,
        title=title_input,
        description=description_input,
        tags_list=tags_list_input,
    )


if __name__ == '__main__':
    # 函数方式调用
    to_douyin(
        vide_file=r'path/to/video',
        title='标题',
        description='描述',
        tags_list=['标签1', '标签2', '标签3']
    )

    # 命令行调用：python main.py path/to/video 标题 描述 标签1,标签2,标签3
    to_douyin_from_cmd()



